package com.roc.admin.infrastructure.repository.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.roc.admin.domain.entity.Dept;
import com.roc.admin.domain.repository.DeptRepository;
import com.roc.admin.infrastructure.mapper.DeptMapper;
import com.roc.admin.infrastructure.persistence.DeptPO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 部门仓储实现类
 */
@Repository
public class DeptRepositoryImpl implements DeptRepository {

    private final DeptMapper deptMapper;

    public DeptRepositoryImpl(DeptMapper deptMapper) {
        this.deptMapper = deptMapper;
    }

    @Override
    public Dept save(Dept dept) {
        DeptPO deptPO = toDeptPO(dept);
        if (deptPO.getId() == null) {
            deptMapper.insert(deptPO);
        } else {
            deptMapper.updateById(deptPO);
        }
        return toDept(deptPO);
    }

    @Override
    public Optional<Dept> findById(Long id) {
        DeptPO deptPO = deptMapper.selectById(id);
        return Optional.ofNullable(deptPO).map(this::toDept);
    }

    @Override
    public List<Dept> findAll() {
        List<DeptPO> deptPOList = deptMapper.selectList(null);
        return deptPOList.stream().map(this::toDept).collect(Collectors.toList());
    }

    @Override
    public List<Dept> findByParentId(Long parentId) {
        LambdaQueryWrapper<DeptPO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DeptPO::getParentId, parentId);
        queryWrapper.orderByAsc(DeptPO::getSort);
        List<DeptPO> deptPOList = deptMapper.selectList(queryWrapper);
        return deptPOList.stream().map(this::toDept).collect(Collectors.toList());
    }

    @Override
    public List<Dept> findByRoleId(Long roleId) {
        List<DeptPO> deptPOList = deptMapper.selectDeptsByRoleId(roleId);
        return deptPOList.stream().map(this::toDept).collect(Collectors.toList());
    }

    @Override
    public void deleteById(Long id) {
        deptMapper.deleteById(id);
    }

    /**
     * 将部门实体转换为持久化对象
     *
     * @param dept 部门实体
     * @return 部门持久化对象
     */
    private DeptPO toDeptPO(Dept dept) {
        if (dept == null) {
            return null;
        }
        DeptPO deptPO = new DeptPO();
        BeanUtils.copyProperties(dept, deptPO);
        return deptPO;
    }

    /**
     * 将持久化对象转换为部门实体
     *
     * @param deptPO 部门持久化对象
     * @return 部门实体
     */
    private Dept toDept(DeptPO deptPO) {
        if (deptPO == null) {
            return null;
        }
        Dept dept = new Dept();
        BeanUtils.copyProperties(deptPO, dept);
        return dept;
    }
}
